package com.holly.unit.deform.modular.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.holly.unit.auth.api.context.LoginContext;
import com.holly.unit.core.pojo.response.ErrorResponseData;
import com.holly.unit.core.pojo.response.ResponseData;
import com.holly.unit.core.pojo.response.SuccessResponseData;
import com.holly.unit.db.api.pojo.page.PageResult;
import com.holly.unit.deform.api.DeformAuthApi;
import com.holly.unit.deform.api.enums.PermissionTypeEnum;
import com.holly.unit.deform.api.pojo.rsp.DeformResult;
import com.holly.unit.deform.entity.DesignFormAuth;
import com.holly.unit.deform.modular.pojo.DesignFormDelRequest;
import com.holly.unit.deform.service.DeformAuthService;
import com.holly.unit.deform.util.DeformAuthUtil;
import com.holly.unit.scanner.api.annotation.ApiResource;
import com.holly.unit.scanner.api.annotation.GetResource;
import com.holly.unit.scanner.api.annotation.PostResource;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.List;

/**
 * 类描述: 表单设计器权限表
 *
 * @author fxr
 * @version 1.0.0
 * @date 2022/4/12 15:24
 */
@RestController
@ApiResource(name = "表单设计器权限表")
@Api(tags = "表单设计器权限表")
public class DeformAuthController {

    @Resource
    private DeformAuthService service;
    @Resource
    private DeformAuthApi api;

    /**
     * 分页列表查询
     *
     * @param designFormAuth
     * @param req
     * @return
     */
    @ApiOperation(value = "分页列表查询", notes = "分页列表查询")
    @GetResource(name = "分页列表查询", path = "/designFormAuth/list")
    public ResponseData queryPageList(DesignFormAuth designFormAuth, HttpServletRequest req) {
        PageResult<DesignFormAuth> pageList = api.page(designFormAuth, req.getParameterMap());
        return new SuccessResponseData(pageList);
    }

    /**
     * 根据 token 查询用户信息以及所拥有的部门
     *
     * @param token
     * @return
     */
    @ApiOperation(value = "查询用户信息部门", notes = "查询用户信息部门")
    @GetResource(name = "查询用户信息部门", path = "/designFormAuth/queryUserByToken")
    public ResponseData queryUserByToken(@RequestParam(name = "token") String token) {
        String username = LoginContext.me().getLoginUser().getAccount();
        return this.queryUser(username);
    }

    /**
     * 根据 username 查询用户信息以及所拥有的部门
     *
     * @param username
     * @return
     */
    @ApiOperation(value = "查询用户信息部门", notes = "查询用户信息部门")
    @GetResource(name = "查询用户信息部门", path = "/designFormAuth/queryUser/{username}")
    public ResponseData queryUser(@PathVariable("username") String username) {
        return new SuccessResponseData(service.getUserInfoByUsername(username));
    }

    /**
     * 根据 desformCode 查询所有权限
     *
     * @param desformCode
     * @param taskId
     * @param group       是否合并数据（默认返回两条数据，合并后只返回 authType=1 的一条数据
     * @return
     */
    @ApiOperation(value = "查询所有权限", notes = "查询所有权限")
    @GetResource(name = "查询所有权限", path = "/designFormAuth/query/{code}")
    public ResponseData queryByCode(
            @PathVariable("code") String desformCode,
            @RequestParam(name = "taskId", required = false) String taskId,
            @RequestParam(name = "group", required = false, defaultValue = "false") Boolean group
    ) {
        if (StrUtil.isEmpty(taskId)) {
            return new SuccessResponseData(service.queryByCode(desformCode, group));
        } else {
            return new SuccessResponseData(service.queryByTaskId(desformCode, taskId));
        }
    }

    /**
     * 根据 desformCode 和 authComKey 查询单个权限
     *
     * @param desformCode
     * @return
     */
    @ApiOperation(value = "查询单个权限", notes = "查询单个权限")
    @GetResource(name = "查询单个权限", path = "/designFormAuth/query/{desformCode}/{authComKey}")
    public ResponseData queryByCodeAndAuthComKey(
            @PathVariable("desformCode") String desformCode,
            @PathVariable("authComKey") String authComKey
    ) {
        return new SuccessResponseData(service.queryByCodeAndAuthComKey(desformCode, authComKey));
    }

    /**
     * 批量更新
     *
     * @param auths
     * @return
     */
    @ApiOperation(value = "批量更新", notes = "批量更新")
    @PostResource(name = "批量更新", path = "/designFormAuth/updateBatch")
    public ResponseData updateBatch(@RequestBody List<DesignFormAuth> auths) {
        service.updateBatch(auths);
        return new SuccessResponseData("更新成功");
    }

    /**
     * 通过 comKey 删除
     *
     * @param auth
     * @return
     */
    @ApiOperation(value = "comKey删除", notes = "comKey删除")
    @PostResource(name = "comKey删除", path = "/designFormAuth/deleteByComKey")
    public ResponseData deleteByComKey(@RequestBody DesignFormAuth auth) {
        LambdaQueryWrapper<DesignFormAuth> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DesignFormAuth::getDesformCode, auth.getDesformCode());
        queryWrapper.eq(DesignFormAuth::getAuthComKey, auth.getAuthComKey());

        if (service.remove(queryWrapper)) {
            return new SuccessResponseData("删除成功!");
        } else {
            return new SuccessResponseData("条件不匹配");
        }
    }

    /**
     * 给字段新增权限
     *
     * @param auth
     * @return
     */
    @ApiOperation(value = "给字段新增权限", notes = "给字段新增权限")
    @PostResource(name = "给字段新增权限", path = "/designFormAuth/addAuth")
    public ResponseData addAuth(@RequestBody DesignFormAuth auth) {
        if (service.initialAuthInfo(auth)) {
            return new SuccessResponseData("新增成功！");
        } else {
            return new SuccessResponseData("新增失败！");
        }
    }



    /**
     * 批量保存或编辑（有 id 的编辑，否则就保存）
     *
     * @param authList
     * @return
     */
    @ApiOperation(value = "批量保存或编辑", notes = "批量保存或编辑")
    @PostResource(name = "批量保存或编辑", path = "/designFormAuth/saveOrUpdateBatch")
    public ResponseData saveOrUpdateBatch(@RequestBody List<DesignFormAuth> authList) {
        boolean ok = service.saveOrUpdateBatch(authList);
        if (ok) {
            return  new SuccessResponseData("修改成功!");
        } else {
            return  new ErrorResponseData("101","修改失败!");
        }
    }

    @ApiOperation(value = "通过id删除", notes = "通过id删除")
    @PostResource(name = "通过id删除", path = "/designFormAuth/delete")
    public ResponseData delete(@RequestBody @Validated(DesignFormDelRequest.delById.class) DesignFormDelRequest request) {
        api.delById(request.getId());
        return new SuccessResponseData(request.getId());
    }


    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @ApiOperation(value = "批量删除", notes = "通过id删除")
    @PostResource(name = "批量删除", path = "/designFormAuth/deleteBatch")
    public ResponseData deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        if (ids == null || "".equals(ids.trim())) {
            return  new ErrorResponseData("101","参数不识别！");
        } else {
            this.service.removeByIds(Arrays.asList(ids.split(",")));
            return  new SuccessResponseData("删除成功!");
        }
    }

    /**
     * 根据 authComKey 批量删除
     *
     * @param desformCode
     * @param authComKeys
     * @return
     */
    @ApiOperation(value = "authComKey批量删除", notes = "authComKey批量删除")
    @PostResource(name = "authComKey批量删除", path = "/designFormAuth/deleteBatchByAuthComKey")
    public ResponseData deleteBatchByAuthComKey(
            @RequestParam(name = "desformCode") String desformCode,
            @RequestParam(name = "authComKeys") String authComKeys
    ) {
        if (StrUtil.isEmpty(authComKeys)) {
            return  new ErrorResponseData("101","authComKeys 不能为空！");
        } else {
            LambdaQueryWrapper<DesignFormAuth> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(DesignFormAuth::getDesformCode, desformCode);
            queryWrapper.in(DesignFormAuth::getAuthComKey, Arrays.asList(authComKeys.split(",")));
            service.remove(queryWrapper);
            return  new SuccessResponseData("删除成功!");
        }
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "通过id查询", notes = "通过id查询")
    @GetResource(name = "通过id查询", path = "/designFormAuth/queryById")
    public ResponseData queryById(@RequestParam(name = "id", required = true) String id) {
        DesignFormAuth designFormAuth = service.getById(id);
        if (designFormAuth == null) {
            return  new ErrorResponseData("101","未找到对应实体");
        } else {
            return  new SuccessResponseData(designFormAuth);
        }
    }

    /**
     * 根据权限类型筛选 角色 授权数据
     *
     * @param designFormAuth
     * @param roleCode
     * @param permissionType
     * @param request
     * @return
     */
    @ApiOperation(value = "根据权限类型筛选权限", notes = "根据权限类型筛选权限")
    @GetResource(name = "根据权限类型筛选权限", path = "/designFormAuth/roleList/{roleCode}/{permissionType}/{desformCode}")
    public ResponseData queryRolePageListByPermissionType(
            DesignFormAuth designFormAuth,
            @PathVariable("roleCode") String roleCode,
            @PathVariable("permissionType") String permissionType,
            @PathVariable("desformCode") String desformCode,
            HttpServletRequest request
    ) {
        String authScopeField = "auth_scope_roles_val";
        DeformResult deformResult = service.buildResultByPermissionType(authScopeField, roleCode, designFormAuth, permissionType, desformCode, request);
        if (deformResult.isSuccess()) {
            return new SuccessResponseData();
        }
        return new ErrorResponseData(deformResult.getCode().toString(),deformResult.getMessage(),deformResult.getResult());
    }

    /**
     * 根据权限类型筛选数据
     *
     * @param designFormAuth
     * @param permissionType
     * @param req
     * @return
     */
    @ApiOperation(value = "根据权限类型筛选数据", notes = "根据权限类型筛选数据")
    @GetResource(name = "根据权限类型筛选数据", path = "/designFormAuth/list/{permissionType}/{desformCode}")
    public ResponseData queryPageListByPermissionType(
            DesignFormAuth designFormAuth,
            @PathVariable("permissionType") String permissionType,
            @PathVariable("desformCode") String desformCode,
            HttpServletRequest req
    ) {
        PermissionTypeEnum perType = PermissionTypeEnum.getByValue(permissionType);
        if (perType != null) {
            PageResult<DesignFormAuth> pageList = api.pageWithPermissionTypeAndDesCode(designFormAuth, req.getParameterMap(), permissionType, desformCode);
            // 由于按钮有可能没有存到数据库，所以查出来的不一定是全部的数据，还需要合并一下
            if (perType == PermissionTypeEnum.BUTTON && StrUtil.isBlank(designFormAuth.getAuthField())) {
                List<DesignFormAuth> allDbList = pageList.getRows();
                List<DesignFormAuth> allButtonList = DeformAuthUtil.getNewButtonList();
                List<DesignFormAuth> assignButtonList = DeformAuthUtil.assignButtonList(allButtonList, allDbList);
                pageList.setRows(assignButtonList);
                pageList.setTotalRows(assignButtonList.size());
            }
            return  new SuccessResponseData(pageList);
        } else {
            return  new ErrorResponseData("101","不识别的permissionType值");
        }
    }

    /**
     * 给字段新增权限
     *
     * @param auth
     * @return
     */
    @ApiOperation(value = "给字段新增权限", notes = "给字段新增权限")
    @PostResource(name = "给字段新增权限", path = "/designFormAuth/addAuth/{permissionType}")
    public ResponseData addAuthByPermissionType(
            @RequestBody DesignFormAuth auth,
            @PathVariable("permissionType") String permissionType
    ) {
        if (service.addAuthByPermissionType(auth, permissionType)) {
            return  new SuccessResponseData("新增成功！");
        } else {
            return  new ErrorResponseData("101","新增失败！");
        }
    }

    /**
     * 编辑
     *
     * @param auth
     * @return
     */
    @ApiOperation(value = "编辑权限", notes = "编辑权限")
    @PostResource(name = "编辑权限", path = "/designFormAuth/editAuthByPermissionType/{permissionType}")
    public ResponseData editAuthByPermissionType(@RequestBody DesignFormAuth auth,@PathVariable("permissionType") String permissionType) {
        if (service.editAuthByPermissionType(auth, permissionType)) {
            return  new SuccessResponseData("新增成功！");
        } else {
            return  new ErrorResponseData("101","新增失败！");
        }
    }

}
